<template>
  <view class="deviceInfo">
    <u-cell-group>
      <u-cell-item
          :arrow="false"
          :value="Bluetooth.device.sn"
          icon="account"
          :title="$t('设备SN')"
      />
      <u-cell-item
          :arrow="false"
          :value="sealInfo.params.device_version.value"
          icon="bag"
          :title="$t('设备版本')"
      />
    </u-cell-group>
  </view>
</template>

<script>
import {
  mapGetters,
  mapMutations
} from "vuex"

export default {
  components: {},
  computed: {
    ...mapGetters(["userInfo", "api", "Bluetooth"])
  },
  data() {
    return {
      end: {
        loading: false
      },
      sealInfo: {
        params: {
          device_version: {
            value: ''
          }
        }
      },
      deviceId: ''
    }
  },
  watch: {},
  onBackPress(options) {
    uni.closeBluetoothAdapter();
    if (options.from === 'navigateBack') {
      return false;
    }
    uni.navigateBack({
      delta: 1
    });
    return true;
  },
  onLoad(e) {
    uni.setNavigationBarTitle({title: this.$t('设备信息')})
    this.deviceId = e.id
    //停止搜索蓝牙
    this.$lizhao.bluetooth.stopBluetoothDevicesDiscovery()
  },
  onReady() {
    this.$lizhao.bluetooth.initParams()
    uni.showLoading({
      title: this.$t('获取设备信息') + '...',
      mask: false
    });
    //获取设备信息
    this.getSealInfo()
    //监听回复
    uni.$off('onBLECharacteristicValueChange')
    uni.$on('onBLECharacteristicValueChange', (res) => {
      if (res.cmd === 128 && res.data.topic === `/sys/e2263a5940a843e3b2f4d4c90a624835/${this.Bluetooth.device.sn}/thing/event/property/post`) {
        uni.hideLoading()
        let payload = JSON.parse(res.data.payload)
        this.sealInfo = payload
        //上报设备版本号
        this.updateSoftVersion()
      } else if (res.cmd === 130 && res.data) {
        if (res.data.event === 'devLocked' && this.end.loading === false) {//设备锁定
          uni.navigateBack({
            delta: 1
          });
          uni.closeBluetoothAdapter();
          setTimeout(() => {
            uni.showToast({
              title: this.$t('设备已锁定'),
              icon: "none"
            });
          }, 500)
        }
      }

    })
  },
  methods: {
    //上报设备版本号
    updateSoftVersion() {
      let req = {
        deviceId: this.deviceId,
        softVersion: this.sealInfo.params.device_version.value
      }
      this.$u.post(this.api.GLOBAL_device_dingSignet_updateSoftVersion, req).then(res => {
        if (res.code === 200) {
        }
      })
    },
    //获取设备信息
    getSealInfo() {
      let payload = {id: "67", method: "thing.service.property.set", params: {}, "version": "1.0"}
      let body = {
        topic: "/sys/e2263a5940a843e3b2f4d4c90a624835/" + this.Bluetooth.device.sn + "/thing/service/property/set",
        payload: JSON.stringify(payload)
      }
      let length = this.$lizhao.scale.switch_sl(JSON.stringify(body).length, 16)// 十进制转十六进制
      let stri = '0'
      for (let i = 0; i < (7 - length.length); i++) {
        stri += '0'
      }
      //计算出body长度
      let len = stri + length//body的长度为39转成4位的16进制为00 00 00 26
      let cmd = '0080'//128转成两位的16进制为00 80
      //body转成16进制 十进制数据转换为16进制
      let body_16 = this.$lizhao.scale.strToHexCharCode(JSON.stringify(body))
      let hex = this.Bluetooth.agreement.magic + cmd + this.Bluetooth.agreement.id + len + body_16
      let arr = this.splitArr(hex)
      //多个指令串行发送，并行可能会失败
      this.writeCmd(arr, 0, '设备信息')
    },
    //arr为hex分割的数组，i为当前数组下标
    async writeCmd(arr, i, text) {
      let res = await this.$lizhao.bluetooth.writeBLECharacteristicValue(arr[i])
      if (res === 'writeBLECharacteristicValue:ok') {
        i++
        if (i > arr.length) {
          return
        }
        this.$lizhao.sleep.sleep(50)
        this.writeCmd(arr, i, text)
      } else {
        this.aginSendFn(text)
      }

    },
    //分割指令每20位分割一下，返回数组
    splitArr(hex) {
      let arr = []
      for (let a = 0; a < Math.ceil(hex.length / 20); a++) {
        let str = hex.slice(a * 20, a * 20 + 20)
        arr.push(str)
      }
      return arr
    },
    //重发机制
    aginSendFn(text) {
      uni.showModal({
        title: this.$t('提示'),
        content: this.$t('系统繁忙'),
        cancelText: this.$t('取消'),
        confirmText: this.$t('重新发送'),
        success: ms => {
          if (ms.confirm) {
            uni.showLoading({
              title: this.$t('重新发送') + '...',
              mask: false
            });
            if (text === '设备信息') {
              this.getSealInfo()
            }
          }
          if (ms.cancel) {
            uni.navigateBack({
              delta: 1
            });
          }
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.deviceInfo {
  background-color: #fff;
  width: 100%;
  height: 100%;
  padding: 0;
  box-sizing: border-box;
}
</style>
